package xyz.csmcool.imserver.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Random;

/**
 * @author 什锦
 * @Package xyz.csmcool.imchat.config
 * @since 2022/8/14 13:54
 */
@Component
public class MyInterceptor  implements HandshakeInterceptor {

    /**
     * 握手前
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("握手开始");
        String uid = "0";
        Integer roomId = 0;
        try {
            String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            String jwtToken = URLDecoder.decode(req.getHeader("sec-websocket-protocol"), "utf-8");
            if(StringUtils.isEmpty(jwtToken) || !jwtToken.startsWith("Bearer")) { return false;}
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken.replace("Bearer", ""));
            Claims claims = claimsJws.getBody();
            uid =  (String)claims.get("id");
            roomId = Integer.valueOf(req.getParameter("roomId"));
        } catch (Exception e) {
            return false;
        }
        attributes.put("uid", Integer.valueOf(uid));
        attributes.put("roomId", roomId);
        System.out.println("用户 token " + uid + " 握手成功！");
        System.out.println("用户进入房间" + roomId);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("........afterHandshake.......");
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            HttpServletResponse resp = ((ServletServerHttpResponse) response).getServletResponse();
            if (!StringUtils.isEmpty(req.getHeader("sec-websocket-protocol"))) {
                resp.addHeader("sec-websocket-protocol", req.getHeader("sec-websocket-protocol"));
            }
        }
        System.out.println("握手完成");
    }
}
